/**
 * 提示框 - 成功
 * @param {Object} text
 * @param {Object} event
 */
function toastSuc(text, event) {
	uni.showToast({
		mask: true,
		title: (!text ? "成功" : text),
		success: () => {
			setTimeout(() => {
				if (event) {
					event()
				}
			}, 1500)
		}
	})
}

/**
 * 提示框 - 没有图标
 * @param {Object} text
 * @param {Object} event
 */
function toastNone(text, event) {
	uni.showToast({
		mask: true,
		icon:"none",
		title: text,
		success: () => {
			setTimeout(() => {
				if (event) {
					event()
				}
			}, 1500)
		}
	})
}

/**
 * 提示框 - 展示成功后返回
 * @param {Object} text
 * @param {Object} params
 */
function toastSucBack(text, emitName, emitValue, event) {
	uni.showToast({
		mask: true,
		title: (!text ? "成功" : text),
		success: () => {
			setTimeout(() => {
				if (emitName) {
					if (Array.isArray(emitName)) {
						emitName.forEach(item => {
							uni.$emit(item, emitValue)
						})
					} else {
						uni.$emit(emitName, emitValue)
					}
				}
				if (event) {
					event()
				} else {
					uni.navigateBack()
				}
			}, 1500)
		}
	})
}

/**
 * 提示框 - 错误
 * @param {Object} text
 * @param {Object} event
 */
function toastErr(text, event) {
	uni.showToast({
		image: "/static/wxicon/error.png",
		mask: true,
		title: (!text ? "错误" : text),
		success: () => {
			setTimeout(() => {
				if (event) {
					event()
				}
			}, 1500)
		}
	})

}

/**
 * 提示框 - 加载处理中
 * @param {Object} title
 */
function toastLoading(title) {
	uni.showLoading({
		title: !title ? `处理中...` : title,
		mask: true
	})
}

/**
 * 提示框 - 隐藏
 */
function toastHide() {
	uni.hideLoading()
	uni.hideToast()
}

/**
 * 模态弹窗 - 温馨提示
 * @param {Object} content
 * @param {Object} confirmEvent
 * @param {Object} cancelEvent
 */
function modalInfo(content, confirmEvent, cancelEvent) {
	uni.showModal({
		title: "温馨提示",
		content: content,
		confirmText: "确认",
		showCancel: cancelEvent ? true : false,
		cancelText: cancelEvent ? "取消" : "",
		success: (res) => {
			if (res.confirm) {
				if (confirmEvent) {
					confirmEvent()
				}
			} else {
				if (cancelEvent) {
					cancelEvent()
				}
			}
		}
	})
}

/**
 * 模态弹窗 - 警告提示
 * @param {Object} content
 */
function modalWarin(content) {
	uni.showModal({
		title: "警告提示",
		content: content,
		confirmText: "确认",
		showCancel: false
	})
}

/**
 * 模态弹窗 - 系统提示
 * @param {Object} content
 */
function modalError(content) {
	uni.showModal({
		title: "系统提示",
		content: content,
		confirmText: "确认",
		showCancel: false
	})
}

/**
 * 将obj1的属性添加到obj2
 * @param {Object} obj1 当前对象
 * @param {Object} obj2 目标对象
 * @param {Object} isToNull 
 */
function obj2obj(obj1, obj2, isToNull) {

	for (let key in obj1) {
		if (!isToNull || isToNull == true) {
			obj2[key] = obj1[key]
		} else {
			if (obj1.hasOwnProperty(key) && !obj1[key]) {
				obj2[key] = obj1[key]
			}
		}
	}
}

/**
 * 对象深度克隆
 * @param {Object} obj
 */
function objDeepClone(obj) {
	if (typeof obj !== "object" || obj === null) {
		return obj;
	}

	let clone = Array.isArray(obj) ? [] : {};

	for (let key in obj) {
		if (obj.hasOwnProperty(key)) {
			clone[key] = deepClone(obj[key]);
		}
	}

	return clone;
}
/**
 * 对象深度合并
 */
function objDeepMerge(target, ...sources) {
	if (!sources.length) {
		return target;
	}

	const source = sources.shift();

	if (typeof target !== "object" || target === null) {
		target = {};
	}

	for (let key in source) {
		if (source.hasOwnProperty(key)) {
			if (typeof source[key] === "object" && source[key] !== null) {
				target[key] = objDeepMerge(target[key], source[key]);
			} else {
				target[key] = source[key];
			}
		}
	}

	return objDeepMerge(target, ...sources);
}
/**
 * 链式读取对象属性
 * @param {Object} obj
 * @param {Object} path
 */
function objGetProperty(obj, path) {
  const keys = path.split(".");
  let value = obj;

  for (let key of keys) {
    if (value && value.hasOwnProperty(key)) {
      value = value[key];
    } else {
      return undefined;
    }
  }

  return value;
}
/**
 * 链式设置对象属性值
 * @param {Object} obj
 * @param {Object} propertyPath
 * @param {Object} value
 */
function objSetProperty(obj, propertyPath, value) {
	const keys = propertyPath.split(".");
	let currentObj = obj;

	for (let i = 0; i < keys.length - 1; i++) {
		const key = keys[i];
		if (!currentObj.hasOwnProperty(key) || typeof currentObj[key] !== "object") {
			currentObj[key] = {};
		}
		currentObj = currentObj[key];
	}

	const lastKey = keys[keys.length - 1];
	currentObj[lastKey] = value;

	return obj;
}

/**
 * 移除空值
 * @param {Object} obj
 */
function removeEmptyValues(obj) {
	for (let key in obj) {
	    if (obj.hasOwnProperty(key)) {
	      if (typeof obj[key] === "object" && obj[key] !== null) {
	        removeEmptyValues(obj[key]);
	        if (Object.keys(obj[key]).length === 0) {
	          delete obj[key];
	        }
	      } else if (obj[key] === null || obj[key] === undefined || obj[key] === "") {
	        delete obj[key];
	      }
	    }
	  }
	  return obj;
}

/**
 * 获取字符串中某个字符数量
 * @param {Object} str 字符串
 * @param {Object} char 某个字符
 */
function countContainsValue(str, char) {
	var count = 0;
	while (str.indexOf(char) != -1) {
		str = str.replace(char, "")
		count++;
	}
	return count;
}

/**
 * 输入分数返回值。用于输入框内固定小数位
 * @param {Object} fenshu 分数
 * @param {Object} fiexd 位数
 */
function getFenshuWidthFiexd(fenshu, fiexd) {
	console.info("getFenshuWidthFiexd:参数", fenshu, fiexd)
	if (!fenshu) {
		return ''
	}
	let result = fenshu

	let fArray = fenshu.split(".")
	console.info("getFenshuWidthFiexd:分组", fArray)
	if (fArray.length == 1) {} else if (fArray.length == 2) {
		let f2 = fArray[1]
		let lCha = f2.length - fiexd
		if (lCha > 0) {
			result = fenshu.substr(0, fenshu.length - lCha)
		}
	} else {
		result = fArray[0] + '.' + fArray[1]
	}

	console.info("getFenshuWidthFiexd:结果", result)
	return result
}

/**
 * 跳转页面
 * @param {Object} url
 * @param {Object} params
 */
function navTo(url, params) {
	let zUrl = url
	if (!params) {
		params = {}
	}
	console.info(params)
	let paramsUrl = ""
	for (let paramKey in params) {
		paramsUrl += paramKey + "=" + params[paramKey] + "&"
	}
	if (paramsUrl.endsWith("&")) {
		paramsUrl = paramsUrl.substr(0, paramsUrl.length - 1)
	}

	if (paramsUrl != "") {
		if (isContainsValue(zUrl, "?")) {
			zUrl += "&" + paramsUrl
		} else {
			zUrl += "?" + paramsUrl
		}
	}
	console.info(zUrl)
	uni.navigateTo({
		url: zUrl,
		success: (res) => {
			console.info("跳转成功", res, url, params)
		},
		fail: (res) => {
			console.info("跳转失败", res, url, params)
		}
	})
}

let sysInfo = uni.getSystemInfoSync()
/**
 * 获取系统信息
 */
function sys() {
	return sysInfo
}

/**
 * 展示客服
 */
function showKefu() {
	uni.showModal({
		title: "客服中心",
		content: "加微信：17329275632",
		confirmText: "复制号码",
		success: (res) => {
			if (res.confirm) {
				uni.setClipboardData({
					data: '17329275632',
					success: () => {
						showToastSuccess("已复制")
					}
				});
			}
		}
	})
}

/**
 * 文件分享
 * @param {Object} url
 * @param {Object} fileName
 */
function fileShare(url, fileName) {
	// let url = "文件url"
	let fileFullPath = wx.env.USER_DATA_PATH + "/" + getUUID(true) + "." + url.split(".")[url.split(".").length - 1]
	console.info("fileFullPath", fileFullPath)
	wx.downloadFile({
		url: url, // 下载url
		filePath: fileFullPath,
		success(res) {
			console.info("下载文档参数", res)
			// 下载完成后转发
			wx.shareFileMessage({
				filePath: fileFullPath,
				fileName: fileName,
				success() {},
				fail: (err) => {
					console.info("分享文档失败", err)
					showModalError("分享文档失败,请联系客服。", JSON.stringify(err))
				}
			})
		},
		fail: (err) => {
			console.info("下载文件失败", err)
			showModalError("下载文件失败,请联系客服。", JSON.stringify(err))
		}
	})
}

/**
 * 文件预览
 * @param {Object} url
 */
function filePreview(url) {
	// this.$common.filePreview("文件网络链接")
	// let fileDir = wx.env.USER_DATA_PATH + "/" + getUUID(true)
	let fileDir = wx.env.USER_DATA_PATH + "/" + url.split("/")[url.split("/").length - 2]
	let fileFullPath = fileDir + "/" + url.split("/")[url.split("/").length - 1]
	console.info("文件全路径", fileFullPath)
	const fs = wx.getFileSystemManager()
	uni.downloadFile({
		url: url, //文件链接
		success: (resDownload) => {
			console.info("下载成功", resDownload)
			//statusCode状态为200表示请求成功，tempFIlePath临时路径
			if (resDownload.statusCode == 200) {
				//保存到本地
				uni.saveFile({
					tempFilePath: resDownload.tempFilePath,
					success: (res) => {
						fs.mkdirSync(fileDir, true)
						fs.copyFile({
							srcPath: res.savedFilePath,
							destPath: fileFullPath,
							success: (res) => {
								console.log("复制成功", res)
								//res.savedFilePath文件的保存路径
								//保存成功并打开文件
								uni.openDocument({
									showMenu: true,
									filePath: fileFullPath,
									success: (res) => console.log('成功打开文档'),
									fail: (err) => {
										console.info("打开文档失败", err)
										showModalError("打开文档失败,请联系客服。",
											JSON.stringify(err))
									}
								})
							},
							fail(err) {
								console.error("复制文档失败", err)
								showModalError("保存文档失败,请联系客服。", JSON.stringify(err))
							}
						})
					},
					fail: (err) => {
						console.info("保存失败", err)
						showModalError("保存文档失败,请联系客服。", JSON.stringify(err))
					}
				})
			}
		},
		fail: (err) => {
			console.info("下载失败", err)
			showModalError("下载文档失败,请联系客服。", JSON.stringify(err))
		}
	})
}

/**
 * 是否是邮件
 * @param {Object} str
 */
function isEmail(str) {
	let email = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
	return email.test(str)
}
/**
 * 是否是手机号
 * @param {Object} str
 */
function isPhone(str) {
	let phone = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
	return phone.test(str)
}
/**
 * 是否身份证号
 * @param {Object} str
 */
function isIdCard(str) {
	let idCard = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
	return idCard.test(str)
}
/**
 * 是否网址
 * @param {Object} str
 */
function isUrl(str) {
	let url = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i
	return url.test(str)
}
/**
 * 是否邮编
 * @param {Object} str
 */
function isPostCode(str) {
	let postCode = /^[1-9]\d{5}$/
	return postCode.test(str)
}
/**
 * 是否QQ号
 * @param {Object} str
 */
function isQQ(str) {
	let qq = /^[1-9][0-9]\d{4,9}$/
	return qq.test(str)
}
/**
 * 是否名字
 * @param {Object} str
 */
function isName(str) {
	let name = /^[\u4e00-\u9fa5]{2,4}$/
	return name.test(str)
}
/**
 * 是否车牌号
 * @param {Object} str
 */
function isCarNo(str) {
	// 新能源
	let xny = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}(([0-9]{5}[DF]$)|([A-HJ-K][A-HJ-NP-Z0-9][0-9]{4}$))/;

	// 燃油车
	let ryc = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-HJ-NP-Z0-9]{4}[A-HJ-NP-Z0-9挂学警港澳]{1}$/;

	return xny.test(str) || ryc.test(str)
}
/**
 * 是否是汉字
 * @param {Object} str
 */
function isChinese(str) {
	return /^[\u4e00-\u9fa5]+$/.test(str);
}
/**
 * 是否是字母
 * @param {Object} str
 */
function isLetter(str) {
	return /^[a-zA-Z]+$/.test(str);
}
/**
 * 是否是字母或者数字
 * @param {Object} str
 */
function isLetterOrNumber(str) {
	return /^[a-zA-Z0-9]+$/.test(str);
}
/**
 * 是否包含值
 * @param {Object} str
 * @param {Object} value
 */
function isContainsValue(str, value) {
	return str.includes(value);
}
/**
 * 数值是否在某个范围内
 * @param {Object} value
 * @param {Object} min
 * @param {Object} max
 */
function isNumInRange(value, min, max) {
	return new RegExp(`^${min}$|^${max}$|^[${min}-${max}]$`).test(value);
}
/**
 * 是否字符串长度是否在某个范围内
 * @param {Object} str
 * @param {Object} min
 * @param {Object} max
 */
function isStrLengthInRange(str, min, max) {
	return new RegExp(`^.{${min},${max}}$`).test(str);
}
/**
 * 是否是数组
 * @param {Object} obj
 */
function isArray(obj) {
	return Array.isArray(obj)
}
/**
 * 是否是Json字符串
 * @param {Object} str
 */
function isJson(str) {
	try {
		JSON.parse(str);
		return true;
	} catch (e) {
		return false;
	}
}
/**
 * 是否是对象
 * @param {Object} value
 */
function isObject(value) {
	return typeof value === "object" && value !== null;
}
/**
 * 是否是字符串
 * @param {Object} value
 */
function isString(value) {
	return typeof value === "string";
}
/**
 * 是否是数字
 * @param {Object} value
 */
function isNumber(value) {
	return typeof value === "number";
}
/**
 * 是否整数
 * @param {Object} value
 */
function isInteger(value) {
	return Number.isInteger(value);
}
/**
 * 是否为空
 * @param {Object} value
 */
function isEmpty(value) {
	if (value === null || value === undefined) {
		return true;
	}
	if (typeof value === "string" && value.trim() === "") {
		return true;
	}
	if (Array.isArray(value) && value.length === 0) {
		return true;
	}
	if (typeof value === "object" && Object.keys(value).length === 0) {
		return true;
	}
	return false;
}
/**
 * 是否普通日期
 * @param {Object} value
 */
function isDate(value) {
	return !isNaN(Date.parse(value));
}
/**
 * 是否十进制数值
 * @param {Object} value
 */
function isDecimal(value) {
	return typeof value === "number" && !isNaN(value) && value % 1 !== 0;
}
/**
 * 是否是金额
 * @param {Object} value
 */
function isAmount(value) {
	const reg = /^(([1-9]\d{0,2}(,\d{3})*)|0)(\.\d{1,2})?$/;
	return reg.test(value);
}
/**
 * 去掉所有空格
 * @param {Object} value
 */
function trimAll(value) {
	return str.split(" ").join("");
}

/**
 * 获取uuid
 * @param {Object} is32 是否32位
 */
function getUUID(is32) {
	var s = [];
	var hexDigits = "0123456789abcdef";
	for (var i = 0; i < 36; i++) {
		s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
	}
	s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
	s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
	s[8] = s[13] = s[18] = s[23] = "-";

	var uuid = s.join("");
	if (is32) {
		uuid = uuid.replace(/-/g, '')
	}
	return uuid
}

/**
 * 设置存储字段值
 * @param {Object} stoKey 存储key
 * @param {Object} propertyPath 属性路径
 * @param {Object} propertyValue 属性值
 */
function setStoFieldValue(stoKey, propertyPath, propertyValue) {
	let data = uni.getStorageSync(stoKey)
	if(!data){
		data = {}
	}
	objSetProperty(data,propertyPath,propertyValue)
	uni.setStorageSync(stoKey, data)
}
/**
 * 获取存储字段值
 * @param {Object} stoKey
 * @param {Object} field
 */
function getStoFieldValue(stoKey, propertyPath) {
	let data = uni.getStorageSync(stoKey)
	if(!data){
		return null
	}
	return objGetProperty(propertyPath)
}

/**
 * 初始化自定义头部高度
 */
function getStatusBarHeight(){
	let systemInfo = uni.getSystemInfoSync()
	let statusBar = 0
	let customBar = 0
	let custom = 0
	// #ifndef MP
	statusBar = systemInfo.statusBarHeight;
	if (systemInfo.platform == 'android') {
		customBar = systemInfo.statusBarHeight + 50;
	} else {
		customBar = systemInfo.statusBarHeight + 45;
	};
	// #endif
	// #ifdef MP-WEIXIN
	statusBar = systemInfo.statusBarHeight;
	custom = wx.getMenuButtonBoundingClientRect();
	customBar = custom.bottom + custom.top - systemInfo.statusBarHeight;
	// #endif       
	// #ifdef MP-ALIPAY
	statusBar = systemInfo.statusBarHeight;
	customBar = systemInfo.statusBarHeight + systemInfo.titleBarHeight;
	// #endif
	
	return {
		statusBar:statusBar,
		customBar:customBar,
		custom:custom
	}
}

const common = {
	toastSuc: toastSuc, //提示框 - 成功
	toastNone:toastNone,//提示框 - 没有图标
	toastSucBack: toastSucBack, //提示框 - 展示成功后返回
	toastErr: toastErr, //提示框 - 错误
	toastLoading: toastLoading, //提示框 - 加载处理中
	toastHide: toastHide, //提示框 - 隐藏

	modalInfo: modalInfo, //模态弹窗 - 温馨提示
	modalWarin: modalWarin, //模态弹窗 - 警告提示
	modalError: modalError, //模态弹窗 - 系统提示

	objDeepClone:objDeepClone,//对象深度克隆
	objDeepMerge:objDeepMerge,//对象深度合并
	objGetProperty:objGetProperty,//链式读取对象属性
	objSetProperty:objSetProperty,//链式设置对象属性值
	obj2obj: obj2obj,//将obj1的属性添加到obj2
	
	removeEmptyValues: removeEmptyValues,//移除空值

	countContainsValue: countContainsValue,//获取字符串中某个字符数量
	getFenshuWidthFiexd: getFenshuWidthFiexd,//输入分数返回值。用于输入框内固定小数位

	sys: sys, //获取系统信息

	showKefu: showKefu,//展示客服

	navTo: navTo,//跳转页面
	fileShare: fileShare,//文件分享
	filePreview: filePreview,//filePreview

	getUUID: getUUID,//获取uuid

	setStoFieldValue: setStoFieldValue,//设置存储字段值
	getStoFieldValue: getStoFieldValue,//获取存储字段值

	isEmail: isEmail, //是否邮箱
	isPhone: isPhone, //是否手机号
	isIdCard: isIdCard, //是否身份证号
	isPostCode: isPostCode, //是否邮编
	isName: isName, //是否姓名
	isUrl: isUrl, //是否网址
	isQQ: isQQ, //是否QQ号
	isCarNo: isCarNo, //是否车牌号
	isChinese: isChinese, //是否汉字
	isLetter: isLetter, //是否字母
	isLetterOrNumber: isLetterOrNumber, //是否是字母或者数字
	isContainsValue: isContainsValue, //是否包含值
	isNumInRange: isNumInRange, //数值是否在某个范围内
	isStrLengthInRange: isStrLengthInRange, //是否字符串长度是否在某个范围内
	isArray: isArray, //是否是数组
	isJson: isJson, //是否是Json字符串
	isObject: isObject, //是否是对象
	isString: isString, //是否是字符串
	isNumber: isNumber, //是否是数字
	isInteger: isInteger, //是否整数
	isEmpty: isEmpty, //是否为空
	isDate: isDate, //是否普通日期
	isDecimal: isDecimal, //是否十进制数值
	isAmount: isAmount, //是否是金额
	trimAll: trimAll, //去掉所有空格
	
	getStatusBarHeight:getStatusBarHeight,//自定义头部高度
}
export default common